package com.ruyuan.eshop.membership.controller;

import com.alibaba.fastjson.JSON;
import com.ruyuan.eshop.common.constants.RocketMqConstant;
import com.ruyuan.eshop.common.core.JsonResult;
import com.ruyuan.eshop.common.exception.BaseBizException;
import com.ruyuan.eshop.common.utils.JsonUtil;
import com.ruyuan.eshop.membership.domain.dto.MembershipAccountDTO;
import com.ruyuan.eshop.membership.domain.entity.MembershipAccountDO;
import com.ruyuan.eshop.membership.mq.event.UserLoginedEvent;
import com.ruyuan.eshop.membership.mq.producer.DefaultProducer;
import com.ruyuan.eshop.membership.service.MembershipAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 发起活动controller
 *
 * @author zhonghuashishan
 */
@Slf4j
@RestController
@RequestMapping("/careerplan/membership")
public class MembershipController {

    @Autowired
    private DefaultProducer defaultProducer;
    @Autowired
    private MembershipAccountService accountService;

    /**
     * 新增一个促销活动
     * @return
     */
    @PostMapping("/triggerUserLoginEvent")
    public JsonResult<Boolean> saveOrUpdatePromotion(Long accountId){
        try {
            MembershipAccountDTO account = accountService.getById(accountId);

            UserLoginedEvent userLoginedEvent = new UserLoginedEvent();
            userLoginedEvent.setAccount(account);

            String userLoginedEventJSON = JsonUtil.object2Json(userLoginedEvent);
            defaultProducer.sendMessage(
                    RocketMqConstant.USER_LOGINED_EVENT_TOPIC,
                    userLoginedEventJSON,
                    "用户登录事件发生了");

            return JsonResult.buildSuccess(true);
        } catch (BaseBizException e) {
            log.error("biz error: request={}", accountId, e);
            return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
        } catch (Exception e) {
            log.error("system error: request={}", accountId, e);
            return JsonResult.buildError(e.getMessage());
        }

    }

}
